<!--
 * @Author: 清酒吖
 * @Date: 2022-02-03 15:59:49
 * @Email:  
 * @LastEditors:  
 * @LastEditTime: 2022-02-07 15:07:26
 * @Description: 
 * @version: x 1.0
-->
<template>
  <div class="app-container">
    <div style="padding-left: 230px; padding-right: 150px">
      <el-steps :active="active" finish-status="success" simple>
        <el-step title="商品的基本信息"></el-step>
        <el-step title="添加商品图片"></el-step>
        <el-step title="商品的sku信息"></el-step>
      </el-steps>
    </div>

    <br />
    <!-- 商品基本信息 -->
    <el-row v-show="active == 1">
      <el-col :span="16" :offset="4">
        <el-form ref="form" label-width="120px">
          <el-form-item label="商品标题">
            <el-input v-model="entity.goods.goodsName"></el-input>
          </el-form-item>
          <el-form-item label="商品副标题">
            <el-input v-model="entity.goods.caption"></el-input>
          </el-form-item>
          <el-form-item label="商品分类">
            <el-select
              placeholder="请选择一级分类"
              v-model="entity.goods.category1Id"
              @change="handleCat1Change"
            >
              <el-option
                v-for="cat in catList1"
                :label="cat.name"
                :value="cat.id"
                :key="cat.id"
              ></el-option>
            </el-select>
            <el-select
              placeholder="请选择二级分类"
              v-model="entity.goods.category2Id"
              @change="handleCat2Change"
            >
              <el-option
                v-for="cat in catList2"
                :label="cat.name"
                :value="cat.id"
                :key="cat.id"
              ></el-option>
            </el-select>
            <el-select
              placeholder="请选择三级分类"
              v-model="entity.goods.category3Id"
              @change="handleCat3Change"
            >
              <el-option
                v-for="cat in catList3"
                :label="cat.name"
                :value="cat.id"
                :key="cat.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品模板">
            <!-- <el-input v-model="entity.goods.typeTemplateId" disabled></el-input> -->
            <el-input v-model="templateName" disabled></el-input>
          </el-form-item>
          <el-form-item label="商品品牌">
            <el-select placeholder="请选择品牌" v-model="entity.goods.brandId">
              <el-option
                v-for="brand in brandList"
                :label="brand.name"
                :value="brand.id"
                :key="brand.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商城价">
            <el-input-number
              :precision="2"
              :step="0.1"
              :max="10000"
              v-model="entity.goods.price"
            ></el-input-number>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="active = 2">下一步</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <!-- 商品图片 -->
    <el-row v-show="active == 2">
      <el-button
        @click="
          imageDialogVisible = true;
          $refs.goodsImg.clearFiles();
        "
        >添加图片</el-button
      >
      <el-col :span="16" :offset="4">
        <el-table :data="imgsList">
          <el-table-column label="图片">
            <template slot-scope="scope">
              <img style="width: 100px" :src="scope.row" />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="操作" width="100">
            <template slot-scope="scope">
              <el-button
                @click="removeImg(scope.$index)"
                type="primary"
                icon="el-icon-delete"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <br />
        <el-button type="primary" @click="active = 1">上一步</el-button>
        <el-button type="primary" @click="active = 3">下一步</el-button>

        <!-- 添加图片dialog -->
        <el-dialog
          title="添加图片"
          :visible.sync="imageDialogVisible"
          :close-on-click-modal="false"
        >
          <el-form ref="brandForm">
            <el-form-item label="商品图片" prop="logo">
              <el-upload
                action="http://localhost:9527/upload/img"
                :headers="headers"
                list-type="picture-card"
                name="file"
                :on-success="uploadSuccess"
                :limit="1"
                ref="goodsImg"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="imageDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addIMG()">确 定</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>

    <!-- 第三步： sku -->
    <el-row v-show="active == 3">
      <!-- 展示规格面板 -->
      <el-col :span="16" :offset="4">
        <div v-for="(spec, index) in specArr" :key="index">
          <span>{{ spec.specName }} </span>
          <el-checkbox
            @change="genSkuList()"
            v-model="opt.choose"
            :key="index"
            v-for="(opt, index) in spec.options"
            >{{ opt.optionName }}</el-checkbox
          >
        </div>
        <el-table style="width: 100%" border :data="entity.skus">
          <!-- <template v-for="(item,index) in skus">
                <el-table-column :prop="item.column_name" :label="item.column_comment" :key="index" v-show="item.column_name != 'id'"></el-table-column>
            </template> -->

          <el-table-column label="规格">
            <template slot-scope="scope">
              <!-- <span>{{
                JSON.stringify(entity.skus[scope.$index].skuSpec)
              }}</span> -->
              <span v-for="(v, k) in scope.row.skuSpec" :key="k">
                {{ k }}:{{ v }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="库存">
            <template slot-scope="scope">
              <el-input v-model="entity.skus[scope.$index].skuStock" />
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格">
            <template slot-scope="scope">
              <el-input v-model="entity.skus[scope.$index].skuPrice" />
            </template>
          </el-table-column>
          <el-table-column prop="tc" label="预警库存">
            <template slot-scope="scope">
              <el-input v-model="entity.skus[scope.$index].skuLowStock" />
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-button type="primary" @click="saveGoods()">保存提交</el-button>
    </el-row>
  </div>
</template>
<script>
import { findCatList } from "@/api/cat";

import { selectSpecAndOptions } from "@/api/goodsSpec";

import { insertGoods } from "@/api/goodsList";

export default {
  data() {
    return {
      headers:{ // 图片上传请求头
        "token":localStorage.getItem("token"),
      },
      active: 1,
      imgsList: [],
      imageDialogVisible: false,
      specArr: [], //规格面板的数据
      chooseSpec: [],

      catList1: [],
      catList2: [],
      catList3: [],
      templateName: "",
      entity: {
        goods: {},
        skus: [{ skuSpec: {}, skuStock: 0, skuLowStock: 0, skuPrice: 0 }], // sku列表
      },
      brandList: [], // 品牌列表
      tname: "",
      imgTmp: "",
    };
  },
  methods: {
    // * 根据parent_id和级别查询分类
    findCatsParentId(pid, level) {
      findCatList(pid).then((res) => {
        if (level == 1) {
          this.catList1 = res.data;
        }
        if (level == 2) {
          this.catList2 = res.data;
        }
        if (level == 3) {
          this.catList3 = res.data;
        }
      });
    },
    // * 当一级分类改变时,查询二级分类
    handleCat1Change(cat1Id) {
      // 使二级分类置空
      //this.entity.goods.category2Id = "";
      this.$set(this.entity.goods, "category2Id", "");
      this.$set(this.entity.goods, "category3Id", "");
      // 查询二级分类
      this.findCatsParentId(cat1Id, 2);
    },
    // * 当二级分类改变时,查询三级分类
    handleCat2Change(cat2Id) {
      // 使三级分类置空
      //this.entity.goods.category3Id = "";
      this.$set(this.entity.goods, "category3Id", "");
      // 查询三级分类
      this.findCatsParentId(cat2Id, 3);
    },
    // 三级分类change事件
    handleCat3Change(cat3Id) {
      // 获取模板id
      this.catList3.forEach((cat) => {
        if (cat.id == cat3Id) {
          // console.log(cat.templateId);
          this.entity.goods.typeTemplateId = cat.templateId;
          if (cat.template) {
            // console.log(cat.template);
            this.templateName = cat.template.name;
            // 从模板中获取品牌列表
            this.brandList = JSON.parse(cat.template.brands);

            // 调用接口查询商品规格信息
            selectSpecAndOptions(cat.template.id).then((res) => {
              this.specArr = res;
            });
          }
        }
      });
    },
    // * 文件上传成功之后的回调
    uploadSuccess(response, file, fileBlacklist) {
      //     console.log(response.data);
      //   this.imgsList.push(response.data);
      this.imgTmp = response.data;
    },
    // * 上传图片确认按钮
    addIMG() {
      if (this.imgTmp) {
        this.imgsList.push(this.imgTmp);
      }
      this.imageDialogVisible = false;
      this.imgTmp = "";
    },
    // 删除图片
    removeImg(index) {
      this.imgsList.splice(index, 1);
    },

    // 动态产生sku列表
    genSkuList() {
      // 清空sku列表
      this.entity.skus = [
        { skuSpec: {}, skuStock: 0, skuLowStock: 0, skuPrice: 0 },
      ];

      this.specArr.forEach((spec) => {
        // 判断当前是否有规格选项被选中
        var flag = false;
        spec.options.forEach((opt) => {
          if (opt.choose) {
            flag = true;
          }
        });

        if (flag) {
          this.entity.skus = this.addRow(
            spec.specName,
            spec.options,
            this.entity.skus
          );
        }
      });
    },
    // 生成新的一行
    addRow(specName, opts, skuList) {
      // specName:口味  opts:[原味,奶香] skuList: [{ skuSpec: {}, skuStock: 0, skuLowStock: 0, skuPrice: 0 }]

      // 临时数组
      var skuArrTemp = [];

      skuList.forEach((sku) => {
        opts.forEach((opt) => {
          if (opt.choose) {
            var skuTemp = JSON.parse(JSON.stringify(sku)); // skuTemp 和 sku长的一样,但不是同一个对象
            skuTemp.skuSpec[specName] = opt.optionName;
            // skuTemp.skuStock=0;
            // skuTemp.skuLowStock=0;
            // skuTemp.skuPrice=0;
            skuArrTemp.push(skuTemp);
          }
        });
      });
      return skuArrTemp;
    },
    // * 添加商品数据
    saveGoods() {
      this.entity.goods.albumPics = this.imgsList.join(",");
      this.entity.skus.forEach(item => {

        item.skuTitle = this.entity.goods.goodsName + "["+item.skuSpec+"]";

        item.skuSpec = JSON.stringify(item.skuSpec)

        
      })
      // 与服务器交互，调用添加方法接口
      insertGoods(this.entity).then((res) => {
        this.$notify({
          title: res.success ? "成功" : "失败",
          message: res.msg,
          type: res.success ? "success" : "error",
          duration: 3000,
        });
        this.$router.push({ path: "/goods/goods-list" });
      });
    },
  },

  created() {
    // * 加载一级分类
    this.findCatsParentId(0, 1);
  },
};
</script>